<?php

namespace app\service\api\GenshinTeam;

use app\model\api\genshin\GenshinStats;
use app\model\api\GenshinAuthor;
use app\model\api\GenshinCategory;
use app\model\api\GenshinRelics;
use app\model\api\GenshinRole;
use app\model\api\GenshinTeamRole;
use app\model\api\GenshinWeapon;
use app\validate\api\GenshinTeam;
use think\facade\Cache;
use think\facade\Db;

class GenshinService
{

    public function saveUserInfo($data){
        $model = new GenshinAuthor();
        $count = $model->where('id',$data['uid'])->count('id');
        if($count>0){
            $model->where('id',$data['uid'])->update([
               'author_name'=>$data['nickname'],
               'author_head'=>$data['avatar'],
            ]);
        }else{
            $model->where('id',$data['uid'])->insert([
               'id'=>$data['uid'],
                'author_name'=>$data['nickname'],
                'author_head'=>$data['avatar'],
            ]);
        }
        return api_success([],1,'存储成功');
    }

    public function getRelicsText()
    {
        $list = (new GenshinStats())->cache(true)->field('name,alias,type')->select()->toArray();
        $array = [
        ];
        foreach ($list as $item) {
            if ($item['type'] == 'substat') {
                $array[$item['type']][] = $item['name'];
            } else {
                $array[$item['type']][] = [
                    'name' => $item['name'],
                    'alias' => $item['alias'],
                ];
            }
        }
        return $array;
    }

    public function getTeamPosition()
    {
        return GenshinTeam::$position_type;
    }

    public function getRoleRelics($role_id)
    {
        $recommend_relics = (new GenshinRole())
            ->cache(true)
            ->where('id', $role_id)
            ->field("recommend_relics,recommend_weapon,weapon")
            ->find();
        if (is_object($recommend_relics)) $recommend_relics = $recommend_relics->toArray();
        if(!$recommend_relics){
            return api_error("角色不存在");
        }
        $recommend_relics = json_decode($recommend_relics['recommend_relics'], true);
        $ids = [];
        foreach ($recommend_relics as $item) {
            $ids = array_merge($ids, array_column($item, 'id'));
        }
        $ids = array_values(array_unique($ids));
        $other = (new GenshinRelics())->cache(true)->field('id,relics_name as name,icon,star as stars')->select()->toArray();
        $recommend = [];
        foreach ($other as &$item) {
            if (in_array($item['id'], $ids)) {
                $recommend[] = $item;
                unset($item);
            }
        }
        return compact('recommend', 'other');
    }

    public function getRoleWeapon($role_id)
    {
        $recommend_weapon = (new GenshinRole())
            ->cache(true)
            ->where('id', $role_id)
            ->field("recommend_relics,recommend_weapon,weapon")
            ->find();
        if (is_object($recommend_weapon)) $recommend_weapon = $recommend_weapon->toArray();
        if(!$recommend_weapon){
            return api_error("角色不存在");
        }
        $recommend_weapon['recommend_weapon'] = json_decode($recommend_weapon['recommend_weapon'], true);
        $ids = array_column($recommend_weapon['recommend_weapon'], 'id');
        $ids = array_values(array_unique($ids));
        $other = (new GenshinWeapon())->cache(true)->where('type_name', $recommend_weapon['weapon'])->field('id as num,weapon_id as id,name,icon,rarity as stars')->select()->toArray();
        $recommend = [];
        foreach ($other as &$item) {
            if (in_array($item['num'], $ids)) {
                $recommend[] = $item;
                unset($item);
            }
        }
        return compact('recommend', 'other');
    }

    public function addTeam($data)
    {
        $model = new \app\model\api\GenshinTeam();
        $count = $model->where('author_id',$data['uid'])->where('team_name',$data['title'])->count();
        if($count>0){
            return api_error('您已发布过同标题组队');
        }
        $instance = (new GenshinCategory())->whereIn('id', $data['instance_ids'])->column("name");
        if ($data['style'] == 0) {
            $number = 4;
        } else {
            $number = 8;
        }
        if (count($data['team']) != $number) {
            return api_error("组队角色人数错误");
        }
        $role_name_id = [
            'top_main_role_id',
            'top_vice_role_id',
            'top_assist1_role_id',
            'top_assist2_role_id',
            'bottom_main_role_id',
            'bottom_vice_role_id',
            'bottom_assist1_role_id',
            'bottom_assist2_role_id',
        ];
        $insert_data = [
            'author_id' => $data['uid'],
            'team_name' => $data['title'],
            'team_desc' => $data['description'],
            'target' => json_encode($data['instance_ids'], 256),
            'keywords' => json_encode($instance, 256),
            'is_admin' => 2,//2表示前台发布
            'status' => 1,//默认已发布
        ];
        $role_ids = array_column($data['team'], 'id');
        $roles = (new GenshinRole())->cache(true)->whereIn('id', $role_ids)->column('id,element,nation', 'id');
        for ($i = 0; $i < $number; $i++) {
            $insert_data[$role_name_id[$i]] = $data['team'][$i]['id'];
            if (!isset($roles[$insert_data[$role_name_id[$i]]])) {
                return api_error('所选角色信息不存在');
            }
        }
        $insert_data['cover'] = $roles[$insert_data['top_main_role_id']]['nation'];
        $insert_data['reaction'] = json_encode($this->reaction([
            $roles[$insert_data['top_main_role_id']]['element'],
            $roles[$insert_data['top_vice_role_id']]['element'],
            $roles[$insert_data['top_assist1_role_id']]['element'],
            $roles[$insert_data['top_assist2_role_id']]['element'],
        ]), JSON_UNESCAPED_UNICODE);
        if ($data['style'] == 1) {
            $insert_data['reaction_bottom'] = json_encode($this->reaction([
                $roles[$insert_data['bottom_main_role_id']]['element'],
                $roles[$insert_data['bottom_vice_role_id']]['element'],
                $roles[$insert_data['bottom_assist1_role_id']]['element'],
                $roles[$insert_data['bottom_assist2_role_id']]['element'],
            ]), JSON_UNESCAPED_UNICODE);
        }
        $insert_data['create_time'] = time();
        $insert_data['update_time'] = time();
        Db::startTrans();
        $insert_id = $model->insertGetId($insert_data);
        $insert_roles = [];
        $i = 0;
        foreach ($data['team'] as $item) {
            if ($i < 4) {
                $type = 1;
            } else {
                $type = 2;
            }
            $insert_roles[] = [
                'role_id' => $item['id'],
                'team_id' => $insert_id,
                'position' => $item['position'],
                'type' => $type,
                'weapon_id' => $item['weapon'],
                'artifact_id' => json_encode($item['artifact'], 256),
                'mainstats' => json_encode([
                    $item['stats']['sandsEon'],
                    $item['stats']['gobletEonothem'],
                    $item['stats']['circletLogos'],
                ], 256),
                'substats' => json_encode($item['stats']['substat'], 256),
                'substats' => json_encode($item['stats']['substat'], 256),
            ];
            $i++;
        }
        (new GenshinTeamRole())->insertAll($insert_roles);
        Db::commit();
        Cache::clear();
        return api_success('', 1, '添加成功');
    }

    public $all_reaction = array(
        'all' => array(
            'title' => '【交织之护】',
            'content' => '所有元素抗性提升15%，物理抗性提升15%'
        ),
        'pyro' => array(
            'title' => '【热诚之火】',
            'content' => '冰元素附着的持续时间下降40%。攻击力提高25%'
        ),
        'anemo' => array(
            'title' => '【迅捷之风】',
            'content' => '体力消耗降低15%，移动速度提升10%，技能冷却时间缩短5%'
        ),
        'geo' => array(
            'title' => '【坚定之岩】',
            'content' => '护盾强效提升15%。此外，角色处于护盾庇护下时，具有如下特性：造成的伤害提升15%；角色对敌人造成伤害时，会使敌人的岩元素抗性降低20%，持续15秒'
        ),
        'electro' => array(
            'title' => '【强能之雷】',
            'content' => '水元素附着持续时间下降40%。触发超导、超载和感电反应时，有100%概率掉落1个雷元素微粒，冷却时间5秒'
        ),
        'hydro' => array(
            'title' => '【愈疗之水】',
            'content' => '火元素附着的持续时间下降40%。受治疗效果提升30%'
        ),
        'cryo' => array(
            'title' => '【粉碎之冰】',
            'content' => '雷元素附着持续时间下降40%。攻击冰元素附着或冻结状态下的敌人时，暴击率提高15%'
        ),
        'dendro' => array(
            'title' => '【蔓生之草】',
            'content' => '元素精通提升50点。触发燃烧、原激化、绽放反应后，队伍中附近的所有角色元素精通提升30点，持续6秒。触发超激化、蔓激化、超绽放、烈绽放反应后，队伍中附近的所有角色元素精通提升20点，持续6秒。以上效果的持续时间单独计算'
        ),
    );

    /**
     * 元素共鸣分析
     * @param $element
     * @return array
     */
    public function reaction($element)
    {
        $reaction = [];
        $new_element = array_unique($element);
        if (count($element) == count($new_element)) {
            $reaction[] = array(
                'name' => $this->all_reaction['all']['title'],
                'element' => $element,
                'description' => $this->all_reaction['all']['content']
            );
        } else {
            $new1_element = array_diff_assoc($element, $new_element);
            foreach ($new1_element as $ele) {
                if (!empty($this->all_reaction[$ele])) {
                    $reaction[$this->all_reaction[$ele]['title']] = array(
                        'name' => $this->all_reaction[$ele]['title'],
                        'element' => [$ele, $ele],
                        'description' => $this->all_reaction[$ele]['content']
                    );
                }
            }
        }
        return array_values($reaction);
    }

    /**
     * 编辑队伍信息
     * @param $data
     * @return array|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editTeam($data)
    {
        $model = new \app\model\api\GenshinTeam();
//        $count = $model->cache(true)->whereNotIn('id',[$data['team_id']])->where('team_name',$data['title'])->count();
//        if($count>0){
//            return api_error('您已发布过同标题组队');
//        }
        $detail = $model->where('author_id', $data['uid'])->where('id', $data['team_id'])->find();
        if (!$detail) {
            return api_error("队伍信息不存在");
        }
        $instance = (new GenshinCategory())->whereIn('id', $data['instance_ids'])->column("name");
        if ($data['style'] == 0) {
            $number = 4;
        } else {
            $number = 8;
        }
        if (count($data['team']) != $number) {
            return api_error("组队角色人数错误");
        }
        $role_name_id = [
            'top_main_role_id',
            'top_vice_role_id',
            'top_assist1_role_id',
            'top_assist2_role_id',
            'bottom_main_role_id',
            'bottom_vice_role_id',
            'bottom_assist1_role_id',
            'bottom_assist2_role_id',
        ];
        $detail->team_name = $data['title'];
        $detail->team_desc = $data['description'];
        $detail->target = json_encode($data['instance_ids'], 256);
        $detail->keywords = json_encode($instance, 256);
        //编辑状态变为未发布
        $detail->is_publish = 0;
        $role_ids = array_column($data['team'], 'id');
        $roles = (new GenshinRole())->cache(true)->whereIn('id', $role_ids)->column('id,element,nation', 'id');
        for ($i = 0; $i < $number; $i++) {
            $detail->{$role_name_id[$i]} = $data['team'][$i]['id'];
            if (!isset($roles[$detail->{$role_name_id[$i]}])) {
                return api_error('所选角色信息不存在');
            }
        }
        $detail->cover = $roles[$detail->top_main_role_id]['nation'];
        $detail->reaction = json_encode($this->reaction([
            $roles[$detail->top_main_role_id]['element'],
            $roles[$detail->top_vice_role_id]['element'],
            $roles[$detail->top_assist1_role_id]['element'],
            $roles[$detail->top_assist2_role_id]['element'],
        ]), JSON_UNESCAPED_UNICODE);
        if ($data['style'] == 1) {
            $detail->reaction_bottom = json_encode($this->reaction([
                $roles[$detail->bottom_main_role_id]['element'],
                $roles[$detail->bottom_vice_role_id]['element'],
                $roles[$detail->bottom_assist1_role_id]['element'],
                $roles[$detail->bottom_assist2_role_id]['element'],
            ]), JSON_UNESCAPED_UNICODE);
        }
        Db::startTrans();
        $detail->save();
        $insert_roles = [];
        $i = 0;
        foreach ($data['team'] as $item) {
            if ($i < 4) {
                $type = 1;
            } else {
                $type = 2;
            }
            $insert_roles[] = [
                'role_id' => $item['id'],
                'team_id' => $data['team_id'],
                'position' => $item['position'],
                'type' => $type,
                'weapon_id' => $item['weapon'],
                'artifact_id' => json_encode($item['artifact'], 256),
                'mainstats' => json_encode([
                    $item['stats']['sandsEon'],
                    $item['stats']['gobletEonothem'],
                    $item['stats']['circletLogos'],
                ], 256),
                'substats' => json_encode($item['stats']['substat'], 256),
                'substats' => json_encode($item['stats']['substat'], 256),
            ];
            $i++;
        }
        (new GenshinTeamRole())->where('team_id', $data['team_id'])->delete();
        (new GenshinTeamRole())->insertAll($insert_roles);
        Db::commit();
        Cache::clear();
        return api_success('', 1, '修改成功');
    }

    public function deleteTeam($data)
    {
        $model = new \app\model\api\GenshinTeam();
        $count = $model->cache(true)->where('id',$data['team_id'])->where('author_id',$data['uid'])->count();
        if($count==0){
            return api_error('您不能删除当前组队信息');
        }
        $model->destroy($data['team_id']);
        Cache::clear();
        return api_success('', 1, '删除成功');
    }
}